package com.xy.webadmin.app.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xy.webadmin.app.model.userEmail.UserEmailReceivedInfo;
import com.xy.webadmin.app.service.*;
import com.xy.webadmin.app.dao.*;
import com.xy.webadmin.upms.service.SysUserService;
import com.xy.webadmin.upms.service.SysDeptService;
import com.xy.common.core.base.dao.BaseDaoMapper;
import com.xy.common.core.constant.GlobalDeletedFlag;
import com.xy.common.core.object.MyRelationParam;
import com.xy.common.core.object.CallResult;
import com.xy.common.core.base.service.BaseService;
import com.xy.common.sequence.wrapper.IdGeneratorWrapper;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 用户邮件信息数据操作服务类。
 *
 * @author xiaoyue
 * @date 2025-05-13
 */
@Slf4j
@Service("userEmailReceivedInfoService")
public class UserEmailReceivedInfoServiceImpl extends BaseService<UserEmailReceivedInfo, Long> implements UserEmailReceivedInfoService {

    @Autowired
    private IdGeneratorWrapper idGenerator;
    @Autowired
    private UserEmailReceivedInfoMapper userEmailReceivedInfoMapper;
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysDeptService sysDeptService;

    /**
     * 返回当前Service的主表Mapper对象。
     *
     * @return 主表Mapper对象。
     */
    @Override
    protected BaseDaoMapper<UserEmailReceivedInfo> mapper() {
        return userEmailReceivedInfoMapper;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public UserEmailReceivedInfo saveNew(UserEmailReceivedInfo userEmailReceivedInfo) {
        userEmailReceivedInfoMapper.insert(this.buildDefaultValue(userEmailReceivedInfo));
        return userEmailReceivedInfo;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveNewBatch(List<UserEmailReceivedInfo> userEmailReceivedInfoList) {
        if (CollUtil.isNotEmpty(userEmailReceivedInfoList)) {
            userEmailReceivedInfoList.forEach(this::buildDefaultValue);
            userEmailReceivedInfoMapper.insertList(userEmailReceivedInfoList);
        }
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean update(UserEmailReceivedInfo userEmailReceivedInfo, UserEmailReceivedInfo originalUserEmailReceivedInfo) {
        // 这里重点提示，在执行主表数据更新之前，如果有哪些字段不支持修改操作，请用原有数据对象字段替换当前数据字段。
        UpdateWrapper<UserEmailReceivedInfo> uw = this.createUpdateQueryForNullValue(userEmailReceivedInfo, userEmailReceivedInfo.getId());
        return userEmailReceivedInfoMapper.update(userEmailReceivedInfo, uw) == 1;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean remove(Long id) {
        return userEmailReceivedInfoMapper.deleteById(id) == 1;
    }

    @Override
    public List<UserEmailReceivedInfo> getUserEmailReceivedInfoList(UserEmailReceivedInfo filter, String orderBy) {
        return userEmailReceivedInfoMapper.getUserEmailReceivedInfoList(filter, orderBy);
    }

    @Override
    public List<UserEmailReceivedInfo> getUserEmailReceivedInfoListWithRelation(UserEmailReceivedInfo filter, String orderBy) {
        List<UserEmailReceivedInfo> resultList = userEmailReceivedInfoMapper.getUserEmailReceivedInfoList(filter, orderBy);
        // 在缺省生成的代码中，如果查询结果resultList不是Page对象，说明没有分页，那么就很可能是数据导出接口调用了当前方法。
        // 为了避免一次性的大量数据关联，规避因此而造成的系统运行性能冲击，这里手动进行了分批次读取，开发者可按需修改该值。
        int batchSize = resultList instanceof Page ? 0 : 1000;
        this.buildRelationForDataList(resultList, MyRelationParam.normal(), batchSize);
        return resultList;
    }

    @Override
    public CallResult verifyRelatedData(UserEmailReceivedInfo userEmailReceivedInfo, UserEmailReceivedInfo originalUserEmailReceivedInfo) {
        String errorMessageFormat = "数据验证失败，关联的%s并不存在，请刷新后重试！";
        //这里是基于字典的验证。
        if (this.needToVerify(userEmailReceivedInfo, originalUserEmailReceivedInfo, UserEmailReceivedInfo::getSysUserId)
                && !sysUserService.existId(userEmailReceivedInfo.getSysUserId())) {
            return CallResult.error(String.format(errorMessageFormat, "系统用户"));
        }
        //这里是基于字典的验证。
        if (this.needToVerify(userEmailReceivedInfo, originalUserEmailReceivedInfo, UserEmailReceivedInfo::getCompanyId)
                && !sysDeptService.existId(userEmailReceivedInfo.getCompanyId())) {
            return CallResult.error(String.format(errorMessageFormat, "公司"));
        }
        return CallResult.ok();
    }

    private UserEmailReceivedInfo buildDefaultValue(UserEmailReceivedInfo userEmailReceivedInfo) {
        if (userEmailReceivedInfo.getId() == null) {
            userEmailReceivedInfo.setId(idGenerator.nextLongId());
        }

        userEmailReceivedInfo.setIsDeleted(GlobalDeletedFlag.NORMAL);
        return userEmailReceivedInfo;
    }
}
